#include "../Headers/proc_control.h"

void
do_job_in_thread(cluster* cl, pthread_t* thread) {
    DEBUG("> do_job_in_thread()\n");
    if (pthread_create(thread, NULL, cl_invoke_in_thread, (void*)cl)) {
        DEBUG("!!!!!!!!!!!!!!!!!! Thread creation failed !!!!!!!!!!!!!!!!\n");
    }
    DEBUG("< do_job_in_thread()\n");
}

void*
cl_invoke_in_thread(void* cl) {
    return (void*)cl_invoke((cluster*)cl);
}

void
init_thread_list(thread_list* list) {
    list->thread = NULL;
    list->retval = NULL;
    list->cl = NULL;
    list->next = NULL;
}

/*
void
cl_process_jobs(cluster* cl) {
    cl_list *cursor;
    thread_list *head, *threads;
    DEBUG("> cl_process_jobs()\n");
    head = (thread_list*)malloc(sizeof(thread_list));
    threads = head;
    init_thread_list(threads);
    cursor = cl->jobs;
    if (!cursor) {
        DEBUG("A cluster with no jobs was invoked.\n");
        free(head);
        return;
    }
    while (1) {
        threads->cl = cursor->cl;  // I'm placing a reference to the cluster in the threads
                                   // list because it will be easier to coordinate the data, even though
                                   // this is not necessary and could be "optimized".
        threads->thread = (pthread_t*)malloc(sizeof(pthread_t));
        do_job_in_thread(threads->cl, threads->thread);

        if (cursor->next == NULL)
            break;
        cursor = cursor->next;
        threads->next = (thread_list*)malloc(sizeof(thread_list));
        threads = threads->next;
        init_thread_list(threads);
    }

    threads = head;

    while (threads != NULL) {
        pthread_join(*threads->thread, &threads->retval);
        head = threads->next;
        cl_remove(threads->cl->name, &cl->jobs);
        threads = threads->next;
    }
    DEBUG("< cl_process_jobs()\n");
}
*/
